package cn.hutool.osc.utils;

import cn.hutool.osc.config.OscConfig;
import com.google.auth.oauth2.GoogleCredentials;
import com.google.cloud.storage.Storage;
import com.google.cloud.storage.StorageOptions;
import software.amazon.awssdk.auth.credentials.AwsBasicCredentials;
import software.amazon.awssdk.auth.credentials.StaticCredentialsProvider;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.s3.S3Client;
import software.amazon.awssdk.services.s3.S3ClientBuilder;

import java.io.FileInputStream;
import java.io.IOException;
import java.net.URI;

public class GCSUtils {

    public S3Client s3Client;
    public Storage storageClient;


    private final String GbucketName;
    private final String Gregion;

    /** 谷歌云兼容s3 */
    public GCSUtils(OscConfig config, S3ClientBuilder builder) {
        Region region = Region.of(config.getRegion());
        AwsBasicCredentials awsCreds = AwsBasicCredentials.create(
                config.getAccessKey(), // AK，即Access Key ID
                config.getSecretKey() // SK，即Secret Access Key
        );
        URI endpointuri = URI.create(config.getEndpoint());
        s3Client = builder.region(region)
                .credentialsProvider(StaticCredentialsProvider.create(awsCreds))
                .endpointOverride(endpointuri)
                .build();
        GbucketName = config.getBucketName();
        Gregion = config.getRegion();
    }

    public GCSUtils(OscConfig config, String jsonPath) {
        GoogleCredentials credentials;
        try (FileInputStream fileInputStream = new FileInputStream(jsonPath);){
            credentials = GoogleCredentials.fromStream(fileInputStream);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        storageClient = StorageOptions.newBuilder()
                .setCredentials(credentials)
                .build()
                .getService();
        GbucketName = config.getBucketName();
        Gregion = config.getRegion();

    }

    public void shutdown() {
        try {
            s3Client.close();
            storageClient.close();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}
